<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>DevOps管理平台</h2>
        <p>欢迎登录</p>
      </div>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-autocomplete
            v-model="loginForm.username"
            :fetch-suggestions="queryUserSuggestions"
            placeholder="请输入用户名"
            size="large"
            class="input-with-icon"
            @select="handleSelect"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-autocomplete>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            show-password
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleLogin"
            class="login-btn"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="form-footer">
        <span>还没有账号？</span>
        <el-link type="primary" @click="goToRegister">立即注册</el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { authAPI } from '../api/auth'

const router = useRouter()
const loginFormRef = ref()
const loading = ref(false)
const userSuggestions = ref([])

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const queryUserSuggestions = (queryString, callback) => {
  const suggestions = userSuggestions.value.filter(item => {
    return item.value.toLowerCase().includes(queryString.toLowerCase())
  })
  callback(suggestions)
}

const handleSelect = (item) => {
  loginForm.username = item.value
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    const response = await authAPI.login({
      username: loginForm.username,
      password: loginForm.password
    })
    
    // 保存token和用户信息
    localStorage.setItem('access_token', response.tokens.access)
    localStorage.setItem('refresh_token', response.tokens.refresh)
    localStorage.setItem('user_info', JSON.stringify(response.user))
    
    ElMessage.success(response.message || '登录成功')
    router.push('/')
    
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loading.value = false
  }
}

const loadUserSuggestions = async () => {
  try {
    const response = await authAPI.getUserSuggestions()
    userSuggestions.value = response.suggestions.map(username => ({
      value: username
    }))
  } catch (error) {
    console.error('获取用户建议失败:', error)
  }
}

const goToRegister = () => {
  router.push('/register')
}

onMounted(() => {
  loadUserSuggestions()
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 10px;
}

.login-header p {
  color: #666;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.input-with-icon {
  width: 100%;
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

.form-footer .el-link {
  margin-left: 5px;
}
</style>
